<script setup lang="ts">
import More from '@/components/More/index.vue'
import Content from '@/components/Content/index.vue'
import ContentTitle from '@/components/ContentTitle/index.vue'
import LittleTitle from './components/LittleTitle/index.vue'
import Pie from './components/Pie/index.vue'
import { Plus } from '@element-plus/icons-vue'
import APIStore from '@/api/store'
import type { ShopResult, SetShopData } from '@/api/store/types'
import { useAuth } from '@/stores/index'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import APICommon from '@/api/common'

const { info } = storeToRefs(useAuth())

const dialogVisible = shallowRef<boolean>(false)

const $router = useRouter()

function handleJumpEnterCompany() {
    $router.push({
        name: 'EnterCompany'
    })
}

function handleJumpEnterPersonal() {
    $router.push({
        name: 'EnterPersonal'
    })
}

/** 店铺基本信息 */
const shopInfo = ref<ShopResult>({})

function getShop() {
    APIStore.getShop().then(({ data }) => {
        shopInfo.value = data
        brief.value = data.brief
        isTransport.value = data.is_transport
    })
} getShop()

const step = computed(() => {
    if (info.value.is_shop == undefined || info.value.is_shop == null) {
        /** 显示按钮 */
        return 1
    } else if (info.value.is_shop == 2) {
        /** 申请未通过 */
        return 2
    } else if (info.value.is_shop == 0) {
        /** 申请中 */
        return 3
    } else if (info.value.is_shop == 1 && info.value.is_shop_show == 1) {
        /** 店铺正常显示 */
        return 4
    } else if (info.value.is_shop == 1 && info.value.is_shop_show == 0) {
        /** 店铺禁止展示 */
        return 5
    }
})


const brief = shallowRef<SetShopData['brief']>('')

function handleChangeBrief() {
    if (shopInfo.value.brief == brief.value) return

    const data: SetShopData = {
        shop_id: shopInfo.value.id,
        brief: brief.value
    }
    APIStore.setShop(data).then(() => {
        ElMessage.success('修改成功')
        getShop()
    })
}


const isTransport = shallowRef<SetShopData['is_transport']>(0)
const loading = shallowRef<boolean>(false)

function beforeChange() {
    loading.value = true

    return new Promise((resolve) => {
        const data: SetShopData = {
            shop_id: shopInfo.value.id,
            is_transport: (Number(!isTransport.value) as SetShopData['is_transport'])
        }
        APIStore.setShop(data).then(() => {
            loading.value = false
            ElMessage.success('修改成功')
            return resolve(true)
        })
    })
}

const refBackground = shallowRef<HTMLInputElement>()

function handleChangeBackground() {
    ElMessageBox.confirm(
        '是否更换店铺背景图？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        refBackground.value?.click()
    }).catch(() => {
        ElMessage.info('已取消')
    })
}

function onUploadBackgroundChange(e: Event) {
    const dom = (e.target as HTMLInputElement)
    if (!dom.files) return
    if (!['image/png', 'image/webp', 'image/jpeg', 'image/gif', 'image/bmp', 'image/svg+xml', 'image/x-icon'].includes(dom.files[0].type)) {
        dom.value = ''
        ElMessage.error('只能上传图片文件，请重新选择文件。')
        return
    }

    const fileSize = dom.files[0].size
    const fileSizeMB = fileSize / (1024 * 1024)
    if (fileSizeMB > 5) return ElMessage.error('上传文件大小不能超过5MB，请重新选择文件。')
    const form = new FormData()
    form.append('file', dom.files[0])

    const changeFileLoading = ElLoading.service({ lock: true })

    APICommon.uploadFile(form).then(({ data }) => {
        const setShopData: SetShopData = {
            shop_id: shopInfo.value.id,
            background: data.file
        }
        return APIStore.setShop(setShopData)
    }).then(() => {
        ElMessage.success('修改成功')
        getShop()
    }).finally(() => {
        changeFileLoading.close()
    })
}

function handleJumpStoreHome() {
    window.open(`${import.meta.env.VITE_APP_WEB_URL}/store-home?shopId=${shopInfo.value.id}`)
}

</script>

<template>
    <div class="store">
        <Content class="content">
            <ContentTitle title="实名入驻店铺信息" content="用于判断此账号的归宿；" />
            <div class="info">
                <div class="label">入驻信息：</div>
                <div class="value top-value">
                    <button class="unnamed" v-if="step == 1 || step == 2" @click="dialogVisible = true">
                        <el-icon color="#FE0000">
                            <Plus />
                        </el-icon>
                        入驻店铺
                    </button>
                    <div class="not-go" v-if="step == 2">审核不通过：{{ info.reason }}</div>
                    <div class="under-review" v-if="step == 3">审核资料中...（2-3个工作日审核完毕）</div>
                    <div class="in-real-name" v-if="step == 4">
                        <span v-if="info.user_type == 'personal'">{{ info?.auth_info?.real_name }} {{ info?.auth_info?.id_card }}</span>
                        <span v-if="info.user_type == 'company'">{{ info?.auth_info?.company_name }} {{ info?.auth_info?.registration_code }}</span>
                    </div>
                </div>
            </div>
        </Content>
        <Content class="content" v-if="step == 4">
            <ContentTitle title="店铺情况"
                content="1、店铺产品情况和搬运/取消搬运开关；<br />2、“作品是否被搬运”关乎您上传的店铺产品是否被其他的人员搬运销售；<br />3、开启“允许搬运”店铺所有的作品将会被搬运，被搬运的产品版权关系不会发生转移；<br />4、被搬运的产品，您无需支付其他的费用；<br />5、不被搬运可以随时关闭搬运功能；关闭后清除所有的搬运关系，请认证对待；" />
            <div class="value">
                <div class="top">
                    <div class="top-left">
                        <LittleTitle title="产品情况" />
                        <Pie :charts="shopInfo?.charts" />
                    </div>
                    <div class="top-right">
                        <LittleTitle title="店内作品是否匀许搬运销售" />
                        <div class="con">
                            <div class="hint">注意：搬运销售指的是在心安元素平台内帮助您销售；</div>
                            <el-switch v-model="isTransport" class="switch"
                                style="--el-switch-on-color: #4095E5; --el-switch-off-color: #ff4949;"
                                active-text="匀许搬运" inactive-text="不被搬运" :inactive-value="0" :active-value="1"
                                :before-change="beforeChange" :loading="loading" />
                        </div>
                    </div>
                </div>
                <div class="bottom">
                    <div class="bottom-left">
                        <LittleTitle title="店铺介绍" />
                        <el-input v-model="brief" :rows="10" type="textarea" placeholder="请输入200字以内的店铺介绍！"
                            style="margin-top: 12px;" maxlength="200" show-word-limit @blur="handleChangeBrief" />
                    </div>
                    <div class="bottom-right">
                        <div class="bottom-right-t">
                            <LittleTitle title="店铺背景图" />
                            <div class="bg" @click="handleChangeBackground">
                                <div class="bg-img">
                                    <img v-if="shopInfo.background" :src="shopInfo.background" alt="背景图">
                                </div>
                            </div>
                            <input ref="refBackground" type="file" @change="onUploadBackgroundChange"
                                style="display: none;" accept="image/*">
                        </div>
                        <div class="bottom-right-b">
                            <LittleTitle title="店铺主页" />
                            <More class="more" title="进入店铺主页" @click="handleJumpStoreHome" />
                        </div>
                    </div>
                </div>
            </div>
        </Content>
        <el-dialog v-model="dialogVisible" title="选择验证的信息类型" width="600" :show-close="false">
            <template #header>
                <DialogClose title="选择验证的信息类型" @close="dialogVisible = false" />
            </template>
            <div class="dialog-btn">
                <button @click="handleJumpEnterPersonal"
                    v-if="info.user_type == 'personal' || !info.user_type">个人认证</button>
                <button @click="handleJumpEnterCompany"
                    v-if="info.user_type == 'company' || !info.user_type">公司认证</button>
            </div>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.store {
    .dialog-btn {
        display: flex;
        flex-direction: column;
        gap: 34px 0;
        padding: 20px 0;

        button {
            width: 307px;
            height: 44px;
            border-radius: 5px 5px 5px 5px;
            background-color: rgba(220, 221, 221, 1);
            color: rgba(136, 136, 136, 1);
            font-size: 14px;
            border: none;
            cursor: pointer;
            transition: all .2s;

            &:hover {
                color: #ffffff;
                background-color: #1684FC;
            }
        }
    }

    .content {
        margin-bottom: 30px;

        .value {
            .top {
                display: flex;
                gap: 0 70px;
                margin-top: 12px;

                .top-left {
                    flex: 3;
                }

                .top-right {
                    flex: 2;

                    .con {

                        .switch {
                            margin-top: 10px;
                            margin-left: 20px;
                        }

                        .hint {
                            color: rgba(187, 187, 187, 1);
                            font-size: 12px;
                            font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
                        }
                    }
                }
            }

            .bottom {
                display: flex;
                gap: 0 70px;

                .bottom-left {
                    flex: 1;
                }

                .bottom-right {
                    flex: 1;


                    .bottom-right-t {
                        .bg {
                            height: 132px;
                            border-radius: 5px;
                            margin-top: 12px;
                            padding-right: 50px;
                            cursor: pointer;

                            .bg-img {
                                width: 100%;
                                height: 100%;
                                background-color: rgb(237, 237, 237);

                                img {
                                    width: 100%;
                                    height: 100%;
                                    object-fit: cover;
                                }
                            }
                        }
                    }
                }

                .bottom-right-b {
                    margin-top: 10px;

                    .more {
                        color: #1684FC;
                        font-size: 14px;
                        margin-top: 15px;
                        font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
                    }
                }
            }
        }

        .info {
            display: flex;
            align-items: center;
            margin: 30px 0;

            .top-value {
                display: flex;
                align-items: center;
            }

            .value {
                .not-go {
                    font-size: 14px;
                    color: #F56C6C;
                }

                .under-review {
                    color: rgba(187, 187, 187, 1);
                    font-size: 14px;
                }

                .unnamed {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    gap: 0 6px;
                    width: 190px;
                    height: 35px;
                    border-radius: 5px;
                    background-color: rgba(255, 255, 255, 1);
                    color: rgba(16, 16, 16, 1);
                    font-size: 14px;
                    border: 1px solid rgba(187, 187, 187, 1);
                    cursor: pointer;
                    margin-right: 25px;
                }

                .in-real-name {
                    color: rgba(64, 149, 229, 1);
                    font-size: 14px;
                }
            }

            .label {
                margin-right: 20px;
                color: rgba(16, 16, 16, 1);
                font-size: 14px;
            }
        }
    }
}
</style>

<style lang="scss">
.store {
    .el-switch__core {
        width: 67px;
    }
}
</style>